package com.kyzh.core.activities

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.view.View
import android.widget.AdapterView
import androidx.core.content.ContextCompat
import com.gushenge.atools.util.ADate
import com.gushenge.core.base.Base
import com.gushenge.core.base.activity.BaseActivity
import com.gushenge.core.beans.Code
import com.gushenge.core.beans.PhoneCodeBean
import com.gushenge.core.dao.GlobalConsts
import com.gushenge.core.dao.GlobalKeys
import com.gushenge.core.dao.MMKVConsts
import com.gushenge.core.impls.UserImpl
import com.gushenge.core.listeners.ResultListener
import com.gushenge.core.md5
import com.gushenge.core.requests.AppRequest
import com.gushenge.core.toast
import com.kyzh.core.R
import com.kyzh.core.adapters.PhoneCodeAdapter
import com.kyzh.core.utils.dip
import com.kyzh.core.utils.isPhone
import com.kyzh.core.utils.loading
import com.rxlife.coroutine.RxLifeScope
import kotlinx.android.synthetic.main.act_bindphonenum.*
import kotlinx.android.synthetic.main.act_bindphonenum.spPhoneCode
import kotlinx.android.synthetic.main.activity_phonelogin.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.jetbrains.anko.textAppearance
import org.jetbrains.anko.toast
import rxhttp.toClass
import rxhttp.wrapper.param.RxHttp

/**
 * Created by Administrator on 2017/9/14 0014.
 */

class BindPhoneActivity : BaseActivity() {

    var time: Job?=null
    private var phoneNub = ""
    internal var sessionid = ""
    var isPhone = true
    private var phoneCode = "+86"
    private lateinit var  beans: ArrayList<PhoneCodeBean>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.act_bindphonenum)
        isPhone = intent.getStringExtra(GlobalKeys.TYPE) == GlobalKeys.PHONE
        initUI()
    }

    private fun initUI() {
        if(MMKVConsts.languageConfig.isNullOrEmpty()||MMKVConsts.languageConfig=="[]"){
            spPhoneCode.visibility=View.GONE
        }else{
            spPhoneCode.visibility=View.VISIBLE
        }
        AppRequest.getPhoneCode {
            beans = this
            val spTypeAdapter = PhoneCodeAdapter(this@BindPhoneActivity, R.layout.item_spinner_code,this)
            spPhoneCode.setPopupBackgroundDrawable(ContextCompat.getDrawable(this@BindPhoneActivity,R.drawable.bg_6dp_white))
            spPhoneCode.adapter = spTypeAdapter
            spPhoneCode.dropDownWidth=dip(300)
            spPhoneCode.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
                override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                    phoneCode = this@getPhoneCode[p2].code
                }

                override fun onNothingSelected(p0: AdapterView<*>?) {
                }

            }
        }
        if (isPhone) {
            titleView.setText(getString(R.string.bindPhone))
            phoneTip.text = getString(R.string.phoneNum)
            phone.hint = getString(R.string.pleaseInputPhoneNum)
            phone.textAppearance = R.style.isPhone
            get.setOnClickListener {
                phoneNub = phone.text.toString().trim()
                if (isPhone(phoneNub)) {
                    getCode(phoneNub)
                } else {
                    getString(R.string.wrongPhone).toast()
                }

            }
        } else {
            titleView.setText(getString(R.string.bindEmail))
            phoneTip.text = getString(R.string.email)
            phone.hint = getString(R.string.pleaseInputEmail)
            phone.textAppearance = R.style.isEmail
            get.setOnClickListener {
                phoneNub = phone.text.toString().trim()
                getCode(phoneNub)
            }
        }
        commit.setOnClickListener {
            time?.cancel()
            get.text = getString(R.string.getVerifyCode)
            get.isClickable = true
            val code = code.text.toString().trim()
            if (code.isNotEmpty()) {
                if (sessionid.isNotEmpty()) {
                    bindPhone(sessionid, phoneNub, code.toInt())
                } else {
                    getString(R.string.pleaseGetVerifyCodeAgain).toast()
                }
            } else {
                getString(R.string.verifyCodeNotNull).toast()
            }
        }

    }
    fun bindPhoneCode(phone: String, listener: ResultListener) {
        val time = ADate.getStampAs13()
        val sign = md5("${MMKVConsts.uid}$time${GlobalKeys.KEY}")
        Log.e("TAG", "bindPhoneCode: $phoneCode", )

        RxLifeScope().launch {
            val result = RxHttp.get("${Base.BASEURL}${GlobalConsts.BIND_PHONE_CODE}")
                .add("uid",MMKVConsts.uid)
                .add("phone", phone)
                .add("t", time)
                .add("sign", sign)
                .add("phoneCode",phoneCode)
                .add("member_id",MMKVConsts.sub)
                .add("language", MMKVConsts.language)
                .toClass<Code<String>>()
                .await()
            result.message.toast()
            if (result.code==1){
                listener.success(result.data?:"")
            }else{
                listener.error(result.message)
            }
        }




//        HttpQuery().bindPhoneCode(
//            GlobalConsts.BIND_PHONE_CODE,
//            MMKVConsts.uid, phone, time, sign,
//            MMKVConsts.sub,
//            MMKVConsts.language).enqueue(object : Callback<Code<String>?> {
//            override fun onFailure(call: Call<Code<String>?>, t: Throwable) {
//                listener.error(t.toString())
//            }
//
//            override fun onResponse(call: Call<Code<String>?>, response: Response<Code<String>?>) {
//                response.body()?:listener.error("验证码获取失败")
//                response.body()?.let {
//                    when(it.code){
//                        1->listener.success(it.data?:"")
//                        else->listener.error(it.message)
//                    }
//                }
//            }
//        })
    }

    private fun getCode(phone: String) {
        val dialog = loading()
        if (isPhone) {
            bindPhoneCode(phone, object : ResultListener {
                @SuppressLint("SetTextI18n")
                override fun success(bean: Any) {
                    sessionid = bean as String
                    dialog.dismiss()
                    get.isClickable = false
                    time = GlobalScope.launch {
                        repeat(60) { time ->
                            val sec = 59 - time
                            if (sec == 0) {
                                val msg = Message()
                                msg.what = 1
                                handler.sendMessage(msg)
                            } else {
                                runOnUiThread { get.text = "${sec}${getString(R.string.countdown)}" }
                            }
                            delay(1000)
                        }
                    }
                }

                override fun error(error: String) {
//                    toast(error)
                    dialog.dismiss()
                }
            })
        } else {
            UserImpl.bindEmailCode(phone, object : ResultListener {
                override fun success(bean: Any) {
                    sessionid = bean as String
                    dialog.dismiss()
                    get.isClickable = false
                    time = GlobalScope.launch {
                        repeat(60) { time ->
                            val sec = 59 - time
                            if (sec == 0) {
                                val msg = Message()
                                msg.what = 1
                                handler.sendMessage(msg)
                            } else {
                                runOnUiThread { get.text = "${sec}${getString(R.string.countdown)}" }
                            }
                            delay(1000)
                        }
                    }
                }

                override fun error(error: String) {
                    toast(error)
                    dialog.dismiss()
                }
            })
        }
    }

    private fun bindPhone(sessionid: String, phone: String, code: Int) {
        val loading = loading()
        if (isPhone) {
            UserImpl.bindPhone(phone, code, sessionid, object : ResultListener {
                override fun success(bean: Any) {
                    loading.dismiss()
                    toast(bean as String)
                    finish()
                }

                override fun error(error: String) {
                    toast(error)
                    loading.dismiss()
                }
            })
        } else {
            UserImpl.bindEmail(phone, code, sessionid, object : ResultListener {
                override fun success(bean: Any) {
                    bean as String
                    loading.dismiss()
                    toast(bean)
                    finish()
                }

                override fun error(error: String) {
                    toast(error)
                    loading.dismiss()
                }
            })
        }

    }

    override fun onDestroy() {
        super.onDestroy()
        time?.cancel()
    }

    @SuppressLint("HandlerLeak")
    private val handler = object :Handler(){
        override fun handleMessage(msg: Message) {
            when(msg.what){
                1->{
                    get.text = getString(R.string.getVerifyCode)
                    get.isClickable = true
                    time?.cancel()
                }
            }
        }
    }
}
